package com.harboursoftware.xstorage.results;

import java.util.Collections;
import java.util.List;

import org.apache.commons.lang.time.DateFormatUtils;

import com.harboursoftware.xstorage.model.XBucket;
import com.harboursoftware.xstorage.model.XObject;
import com.harboursoftware.xstorage.model.XUser;
import com.harboursoftware.xstorage.util.DateUtils;

/**
 * 
 * @author Simon Leung
 * @since 0.1
 */
public class GetBucketResult extends XMLResult {

	private XBucket bucket;
	private String prefix;
	private String marker;
	private int maxKeys;
	
	public GetBucketResult() {
	}
	
	public GetBucketResult(XBucket bucket) {
	    this.bucket = bucket;
	}
	
	@Override
	public String toXML() {
	    
	    
		StringBuilder strBuilder = new StringBuilder();
		strBuilder
				.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>")
				.append("<ListBucketResult xmlns=\"http://s3.amazonaws.com/doc/2006-03-01\">")
				.append("<Name>").append(bucket.getName()).append("</Name>");
		
		if (prefix == null) {
			strBuilder.append("<Prefix/>");
		} else {
			strBuilder.append("<Prefix>").append(prefix).append("</Prefix>");
		}

		if (marker == null) {
			strBuilder.append("<Marker/>");
		} else {
			strBuilder.append("<Marker>").append(marker).append("</Marker>");
		}

		boolean isTruncated = bucket.getObjects().size() < bucket.getSize();
		
		strBuilder
				.append("<MaxKeys>").append(maxKeys).append("</MaxKeys>")
				.append("<IsTruncated>").append(isTruncated).append("</IsTruncated>");

		for (XObject object : bucket.getObjects()) {
			XUser owner = object.getOwner();
			String lastModified = DateFormatUtils.format(object.getLastModified(), DateUtils.PATTERN_ISO8601);
			strBuilder
					.append("<Contents>")
					.append("<Key>").append(object.getKey()).append("</Key>")
					.append("<LastModified>").append(lastModified).append("</LastModified>")
					.append("<ETag>").append("&quot;").append(object.getEtag()).append("&quot;").append("</ETag>")
					.append("<Size>").append(object.getLength()).append("</Size>")
					.append("<StorageClass>STANDARD</StorageClass>")
					.append("<Owner>")
					.append("<ID>").append(owner.getId()).append("</ID>")
					.append("<DisplayName>").append(owner.getDisplayName()).append("</DisplayName>")
					.append("</Owner>")
					.append("</Contents>");
		}

		strBuilder.append("</ListBucketResult>");
		return strBuilder.toString();
	}

	public XBucket getBucket() {
		return bucket;
	}

	public void setBucket(XBucket bucket) {
		this.bucket = bucket;
	}

	public String getPrefix() {
		return prefix;
	}

	public void setPrefix(String prefix) {
		this.prefix = prefix;
	}

	public String getMarker() {
		return marker;
	}

	public void setMarker(String marker) {
		this.marker = marker;
	}

	public int getMaxKeys() {
		return maxKeys;
	}

	public void setMaxKeys(int maxKeys) {
		this.maxKeys = maxKeys;
	}
}
